package com.imay.live.fragment;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.R;
import com.imay.live.activity.dynamics.SearchActivity;
import com.imay.live.activity.family.FamilyHomeActivity;
import com.imay.live.adapter.family.SearchFamilyAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.model.FamilyGroup;
import com.imay.live.model.FamilyModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.custom.LoadRefreshViewControl;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/9/1 0001.
 */

public class SearchFamilyFragment extends BaseRequestFragment {

    private RecyclerView mrecyclerView;
    private ArrayList<MultiItemEntity> suggestlist;
    private ArrayList<MultiItemEntity> mdatas;
    private SearchFamilyAdapter mAdapter;
    private FrameLayout container;
    private LoadRefreshViewControl loadViewControl;
    private String name;
    private int count = 15;

    public static SearchFamilyFragment newInstance() {
        return new SearchFamilyFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.searchfamily_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        container = $(R.id.container);
        suggestlist = new ArrayList<>();
        mdatas = new ArrayList<>();
        mAdapter = new SearchFamilyAdapter(mdatas);
        loadViewControl = new LoadRefreshViewControl(getContext(), mAdapter, count);
        mrecyclerView = loadViewControl.addLoadView(container, new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                if (TextUtils.isEmpty(name)) {
                    if (suggestlist.isEmpty()) {
                        refreshLoad();
                    } else {
                        loadViewControl.refreshLoadView(suggestlist, ResultCode.CodeSuccess);
                    }
                } else {
                    searchFamily(name);
                }
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                if (TextUtils.isEmpty(name)) {
                } else {
                    moreLoad(mAdapter.getData().size(), name);
                }
            }
        }, false);
        loadViewControl.setError(getResources().getString(R.string.search_nouser));
        WrapContentLinearLayoutManager wrapContentLinearLayoutManager
                = new WrapContentLinearLayoutManager(getActivity());
        mrecyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        mrecyclerView.setHasFixedSize(true);
        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MobclickAgent.onEvent(getActivity(), "search_result_family");
                if (adapter.getItem(position) instanceof FamilyModel) {
                    FamilyModel familyModel = (FamilyModel) adapter.getItem(position);
                    FamilyHomeActivity.startActivity(getActivity(), FamilyHomeActivity.OTHERS, familyModel);
                }
            }
        });
        mrecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                ((SearchActivity) getActivity()).setDefault();
            }
        });
        mAdapter.bindToRecyclerView(mrecyclerView);
        if (suggestlist.isEmpty()) {
            refreshLoad();
        } else {
            loadViewControl.refreshLoadView(suggestlist, ResultCode.CodeSuccess);
        }
    }

    private void refreshLoad() {
        loadViewControl.setEnableLoadmore(false);
        ProtoRequestHelper.task(ProtoHttpFactory.suggestFamily(0, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {

                try {
                    Result<FamilyGroup> result = JSON.parseObject(data, new TypeReference<Result<FamilyGroup>>() {
                    }.getType());
                    suggestlist.clear();
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        suggestlist.addAll(result.data.getFamilys());
                    }
                    loadViewControl.refreshLoadView(suggestlist, result.result);
                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
                loadViewControl.setEnableLoadmore(false);
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.setError(getResources().getString(R.string.search_nouser));
            }
        });

    }


    /**
     * @param name
     */
    public void searchFamily(String name) {
        this.name = name;
        loadViewControl.setEnableLoadmore(true);
        refreshLoad(name);
    }

    private void moreLoad(int index, final String name) {
        ProtoRequestHelper.task(ProtoHttpFactory.searchFamily(name, index, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<FamilyGroup> result = JSON.parseObject(data, new TypeReference<Result<FamilyGroup>>() {
                    }.getType());
                    loadViewControl.moreLoadView((ArrayList<? extends MultiItemEntity>) result.data.getFamilys(), result.result);
                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.loadError();
            }
        });
    }

    private void refreshLoad(final String name) {
        if (TextUtils.isEmpty(name)) {
            if (suggestlist.isEmpty()) {
                refreshLoad();
            } else {
                loadViewControl.refreshLoadView(suggestlist, ResultCode.CodeSuccess);
            }
        } else {
            ProtoRequestHelper.task(ProtoHttpFactory.searchFamily(name, 0, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    try {
                        Result<FamilyGroup> result = JSON.parseObject(data, new TypeReference<Result<FamilyGroup>>() {
                        }.getType());
                        loadViewControl.refreshLoadView((ArrayList<? extends MultiItemEntity>) result.data.getFamilys(), result.result);
                    } catch (Exception e) {
                        loadViewControl.setError(getResources().getString(R.string.search_nouser));
                    }
                }

                @Override
                public void onRequestError(String command, int code, String message) {
                    loadViewControl.loadError();
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isVisibleToUser) {
            MobclickAgent.onEvent(getActivity(), "search_user");
            MobclickAgent.onPageStart(getClass().getSimpleName());
        } else {
            MobclickAgent.onPageEnd(getClass().getSimpleName());
        }
    }
}
